using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using Soveryn.Commerce.API;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;

namespace Soveryn.Commerce.Pages
{
    public partial class Item : PageBaseClass
    {

        protected new void Page_PreInit(object sender, EventArgs e)
        {

            Website = WebsiteData.WebsiteDetail(); //we call this again in the baseclass because event handling is weird
            PageID = Website.ItemTemplatePageID.Value;

            base.Page_PreInit(sender, e);

        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack || ItemDataSet == null || !DataUtils.HasRecords(ItemDataTable) || (Item.ItemDisplayStatus < (int)Enums.DisplayRights.Everyone && !EmployeeLoggedIn))
            {
                ItemPanel.Visible = false;
                ItemNotFoundLabel.Visible = true;
                return;
            }

            if (DataUtils.HasRecords(ItemSKUPropertyNamesDataTable) && DataUtils.HasRecords(ItemSKUPropertyValuesDataTable))
            {
                DataRelation SKUPropertyName = new DataRelation("SKUPropertyName", ItemSKUDataTable.Columns["ItemSKUID"], ItemSKUPropertyNamesDataTable.Columns["ItemSKUID"], true);
                ItemDataSet.Relations.Add(SKUPropertyName);

                DataColumn[] parentColumns = { ItemSKUPropertyNamesDataTable.Columns["PropertyNameID"], ItemSKUPropertyNamesDataTable.Columns["ItemSKUID"] };
                DataColumn[] childColumns = { ItemSKUPropertyValuesDataTable.Columns["PropertyNameID"], ItemSKUPropertyValuesDataTable.Columns["ItemSKUID"] };

                DataRelation PropertyNameValue = new DataRelation("PropertyNameValue", parentColumns, childColumns, true);
                ItemDataSet.Relations.Add(PropertyNameValue);

            }

            if (DataUtils.HasRecords(ItemSKUDataTable))
            {
                if (String.IsNullOrEmpty(Item.ItemSKUDisplayType) || Item.ItemSKUDisplayType == "HTMLLIST")
                {
                    ItemSKUListPanel.Visible = true;
                    ItemSKUDataTable.DefaultView.RowFilter = "SKUDisplayStatus = " + ((int)Enums.DisplayRights.Everyone).ToString();
                    ItemSKURepeater.DataSource = ItemSKUDataTable.DefaultView;
                    ItemSKURepeater.DataBind();
                }
                else if (Item.ItemSKUDisplayType == "DROPDOWNLIST")
                {
                    ItemSKUDropDownPanel.Visible = true;
                    foreach (DataRow itemSKURow in ItemSKUDataTable.Rows)
                    {
                        Soveryn.Commerce.Shared.ItemSKUProperties itemSKUProperties = Soveryn.Commerce.Shared.ItemSKUProperties.Create(itemSKURow);
                        if (itemSKUProperties.SKUDisplayStatus == 3)
                            ItemSKUDropDown.Items.Add(new ListItem(itemSKUProperties.SKUName + " (" + itemSKUProperties.SKUUnitPrice_Calc.Value.ToString("C") + ")", itemSKUProperties.ItemSKUID));
                    }
                }
            }

            if (String.IsNullOrEmpty(Item.ItemImageFile))
                Item.ItemImageFile = "lostImage.jpg";

            if (!String.IsNullOrEmpty(Item.ItemImageFile))
            {

                string mainImage = "/ProductImagesCache/large-" + Item.ItemImageFile;
                ExecuteScript("setItemImage('" + mainImage + "', '" + Item.ItemImageAlt + "', '" + Item.ItemName + "');");

                if (DataUtils.HasRecords(ItemImages))
                {
                    if (ItemImages.Rows.Count > 0)
                    {

                        MainItemImage.ImageUrl = mainImage;
                        MainItemImageHyperLink.Attributes["onclick"] = "setItemImage('" + mainImage + "', '" + Item.ItemImageAlt + "', '" + Item.ItemName + "');";
                        MainItemImageHyperLink.Visible = true;

                        ImageGalleryRepeater.DataSource = ItemImages;
                        ImageGalleryRepeater.DataBind();
                    }
                }

            }

            ItemNameLiteral.Text = Item.ItemName;
            ItemSummaryLiteral.Text = Item.ItemSummary;
            ItemDescriptionLiteral.Text = Item.ItemDescription;

        }

        protected void ImageGalleryRepeater_ItemDataBound(Object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            DataRowView DR = (DataRowView)(e.Item.DataItem);
            ItemImageProperties item = ItemImageProperties.Create(DR.Row);

            Image ItemImage = (Image)e.Item.FindControl("ItemImage");
            HyperLink ItemImageHyperLink = (HyperLink)e.Item.FindControl("ItemImageHyperLink");

            ItemImage.ImageUrl = "/ProductImagesCache/medium-" + item.ImageFile;
            ItemImageHyperLink.Attributes["onclick"] = "setItemImage('" + "/ProductImagesCache/large-" + item.ImageFile + "', '" + item.ImageAlt + "', '" + Item.ItemName + "');";

        }

        protected void ItemSKURepeater_ItemDataBound(Object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {

            DataRowView DR = (DataRowView)(e.Item.DataItem);
            ItemSKUProperties sku = ItemSKUProperties.Create(DR.Row);

            HiddenField ItemSKUIDHiddenField = (HiddenField)e.Item.FindControl("ItemSKUIDHiddenField");
            Image SKUImage = (Image)e.Item.FindControl("SKUImage");
            Literal SKUNameLiteral = (Literal)e.Item.FindControl("SKUNameLiteral");
            Literal SKULiteral = (Literal)e.Item.FindControl("SKULiteral");
            Literal SKUDescriptionLiteral = (Literal)e.Item.FindControl("SKUDescriptionLiteral");
            Literal SKUUnitPrice_CalcLiteral = (Literal)e.Item.FindControl("SKUUnitPrice_CalcLiteral");
            Literal SKUOriginalPriceLiteral = (Literal)e.Item.FindControl("SKUOriginalPriceLiteral");
            Panel SKUOptionsPanel = (Panel)e.Item.FindControl("SKUOptionsPanel");
            Repeater PropertyRepeater = (Repeater)e.Item.FindControl("PropertyRepeater");
            LinkButton ItemSKUListAddToCartButton = (LinkButton)e.Item.FindControl("ItemSKUListAddToCartButton");
            TextBox QuantityTextBox = (TextBox)e.Item.FindControl("QuantityTextBox");
            RangeValidator QuantityTextBoxRangeValidator = (RangeValidator)e.Item.FindControl("QuantityTextBoxRangeValidator");

            if (!String.IsNullOrEmpty(sku.SKUImageFile))
            {

                SKUImage.Visible = true;
                SKUImage.ImageUrl = "/ProductImagesCache/small-" + sku.SKUImageFile;
                SKUImage.AlternateText = sku.SKUImageAlt;

            }

            ItemSKUListAddToCartButton.ValidationGroup = "VG" + sku.ItemSKUID;
            QuantityTextBox.ValidationGroup = ItemSKUListAddToCartButton.ValidationGroup;
            QuantityTextBoxRangeValidator.ValidationGroup = ItemSKUListAddToCartButton.ValidationGroup;

            ItemSKUIDHiddenField.Value = sku.ItemSKUID;
            SKUNameLiteral.Text = sku.SKUName;
            SKUDescriptionLiteral.Text = sku.SKUDescription;
            SKUUnitPrice_CalcLiteral.Text = sku.SKUUnitPrice_Calc.Value.ToString("C");
            SKULiteral.Text = sku.SKU;

            if (sku.SKUSalePrice > 0)
                SKUOriginalPriceLiteral.Text = "<span class='OriginalPrice'>" + sku.SKUOriginalPrice.Value.ToString("C") + "</span>";

            DataRow[] propNames = DR.Row.GetChildRows("SKUPropertyName");
            if (propNames.Length > 0)
            {

                SKUOptionsPanel.Visible = true;
                PropertyRepeater.DataSource = propNames;
                PropertyRepeater.DataBind();
            }

        }

        protected void PropertyRepeater_ItemDataBound(Object sender, RepeaterItemEventArgs e)
        {

            DataRow row = (DataRow)(e.Item.DataItem);
            Soveryn.Commerce.Shared.PropertyNameProperties propName = Soveryn.Commerce.Shared.PropertyNameProperties.Create(row);

            HiddenField PropertyNameHiddenField = (HiddenField)e.Item.FindControl("PropertyNameHiddenField");
            DropDownList PropertyValueDropDownList = (DropDownList)e.Item.FindControl("PropertyValueDropDownList");
            //HiddenField PropertyNameIDHiddenField = (HiddenField)e.Item.FindControl("PropertyNameIDHiddenField");
            RequiredFieldValidator PropertyValueDropDownRequired = (RequiredFieldValidator)e.Item.FindControl("PropertyValueDropDownRequired");

            PropertyNameHiddenField.Value = propName.PropertyName;
            PropertyValueDropDownList.Items.Add(new ListItem("Select " + propName.PropertyName, "na"));
            //PropertyNameIDHiddenField.Value = propName.PropertyNameID;

            PropertyValueDropDownList.ValidationGroup = "VG" + row["ItemSKUID"].ToString();
            PropertyValueDropDownRequired.ValidationGroup = PropertyValueDropDownList.ValidationGroup;

            DataRow[] propertyRows = row.GetChildRows("PropertyNameValue");

            foreach (DataRow propertyRow in propertyRows)
            {

                Soveryn.Commerce.Shared.PropertyValueProperties property = Soveryn.Commerce.Shared.PropertyValueProperties.Create(propertyRow);
                string dropdownValueStringBuilder = StringUtils.EncodeTo64(property.PropertySurcharge.ToString()) + "|";
                dropdownValueStringBuilder += StringUtils.EncodeTo64(property.PropertyValue.ToString()) + "|";
                dropdownValueStringBuilder += StringUtils.EncodeTo64(property.PropertyValueID.ToString()) + "|";
                dropdownValueStringBuilder += StringUtils.EncodeTo64(property.PropValIntegrationCode.ToString());

                string dropdownTextStringBuilder = property.PropertyValue.ToString();
                if (property.PropertySurcharge.Value != 0)
                    dropdownTextStringBuilder += " (+" + property.PropertySurcharge.Value.ToString("C") + ")";

                PropertyValueDropDownList.Items.Add(new ListItem(dropdownTextStringBuilder, dropdownValueStringBuilder));
            }

        }

        protected void ItemSKUDropDownAddToCartButton_Click(object sender, EventArgs e)
        {

            Soveryn.Commerce.Shared.API.Call(CustomerAPIURL, "CartLineAdd", new
            {
                WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                CustomerCartSessionID = CustomerCartSessionID,
                ItemSKUID = ItemSKUDropDown.SelectedValue,
                Quantity = Convert.ToInt32(ItemSKUDropDownQuantityTextBox.Text),
                PropertySurchargeTotal = 0.0m,
                PropertyXML = ""
            }, false, false);


            Response.Redirect("/Cart.aspx", true);

        }

        protected void ItemSKUListAddToCartButton_Click(object sender, EventArgs e)
        {

            LinkButton button = (LinkButton)sender;

            TextBox QuantityTextBox = (TextBox)button.Parent.FindControl("QuantityTextBox");
            HiddenField ItemSKUIDHiddenField = (HiddenField)button.Parent.FindControl("ItemSKUIDHiddenField");
            Panel SKUOptionsPanel = (Panel)button.Parent.FindControl("SKUOptionsPanel");
            Repeater PropertyRepeater = (Repeater)button.Parent.FindControl("PropertyRepeater");

            decimal PropertySurchargeTotal = 0;
            string PropertyXML = null;

            if (SKUOptionsPanel.Visible)
            {

                decimal Surcharge = 0;
                PropertyXML = "<SKUProperties>";
                foreach (RepeaterItem repeaterItem in PropertyRepeater.Items)
                {
                    //Literal PropertyNameLiteral = (Literal)repeaterItem.FindControl("PropertyNameLiteral");
                    DropDownList PropertyValueDropDownList = (DropDownList)repeaterItem.FindControl("PropertyValueDropDownList");
                    HiddenField PropertyNameIDHiddenField = (HiddenField)repeaterItem.FindControl("PropertyNameIDHiddenField");
                    HiddenField PropertyNameHiddenField = (HiddenField)repeaterItem.FindControl("PropertyNameHiddenField");


                    string[] SelectedValueCollection = PropertyValueDropDownList.SelectedValue.Split('|');

                    string surcharge = StringUtils.DecodeFrom64(SelectedValueCollection[0]);
                    string propertyValue = StringUtils.DecodeFrom64(SelectedValueCollection[1]);
                    string propertyValueID = StringUtils.DecodeFrom64(SelectedValueCollection[2]);
                    string propValIntegrationCode = StringUtils.DecodeFrom64(SelectedValueCollection[3]);


                    PropertyXML += "<SKUProperty>";
                    PropertyXML += "<PropertyName>" + PropertyNameHiddenField.Value + "</PropertyName>";
                    PropertyXML += "<PropertyValue>" + propertyValue + "</PropertyValue>";
                    PropertyXML += "<PropertyValueID>" + propertyValueID + "</PropertyValueID>";
                    PropertyXML += "<PropertyValueAccountingCode>" + propValIntegrationCode + "</PropertyValueAccountingCode>";
                    PropertyXML += "<Surcharge>" + surcharge + "</Surcharge>";
                    PropertyXML += "</SKUProperty>";

                    Surcharge += Math.Abs(Convert.ToDecimal(surcharge));

                }
                PropertyXML += "</SKUProperties>";
                PropertySurchargeTotal = Surcharge;

            }


            Soveryn.Commerce.Shared.API.Call(CustomerAPIURL, "CartLineAdd", new
            {
                WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                CustomerCartSessionID = CustomerCartSessionID,
                ItemSKUID = ItemSKUIDHiddenField.Value,
                Quantity = Convert.ToInt32(QuantityTextBox.Text),
                PropertySurchargeTotal = 0.0m,
                PropertyXML = PropertyXML
            }, false, false);

            ExecuteScript("$(function(){$.fancybox({ onClosed:function(){window.location.reload();}, width: 800, height: 650, overlayColor: '#000', type: 'iframe', href: '/MiniCart.aspx' })});");

        }

    }
}